<!--
 * @author  dumeng
新建/编辑专项答题
-->
<template>
  <section class="special-manage">
    <div class="manage-title">新建/编辑专项答题</div>

    <section class="manage-main">
      <el-form ref="form" v-loading="formloading" :model="form" :rules="rules" label-width="150px" class="main-form">
        <el-form-item label="活动类型" prop="classifyId">
          <el-radio-group v-model="form.classifyId">
            <el-radio
              v-for="(item, index) in dict.HDZXFXPC"
              :key="index"
              :label="item.dictValue"
            >{{ item.dictName }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="活动名称" prop="activityName">
          <el-input v-model="form.activityName" placeholder="请输入活动名称" />
        </el-form-item>
        <el-form-item label="活动图片" prop="activityImg">
          <image-upload
            :key="upload.imagecropperKey"
            v-model="form.activityImg"
            :preview-id="upload.viewId"
            :forever="true"
            :width="750"
            :view="upload.view"
            :height="480"
            :no-circle="true"
            :no-rotate="false"
            lang-type="zh"
            :is-oss="upload.isOss"
            @changeOssPath="(path) =>{upload.viewId = path}"
          />
        </el-form-item>
        <el-form-item label="活动背景色" prop="activityBackgroundColor">
          <el-color-picker v-model="form.activityBackgroundColor" />
        </el-form-item>
        <el-form-item label="活动时间" required>
          <el-col :span="11">
            <el-form-item label prop="activityStartTime">
              <el-date-picker
                v-model="form.activityStartTime"
                type="datetime"
                :picker-options="pickeroptionsstart"
                placeholder="选择日期"
                style="width: 100%;"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col class="line" :span="2">-</el-col>
          <el-col :span="11">
            <el-form-item label prop="activityEndTime">
              <el-date-picker
                v-model="form.activityEndTime"
                type="datetime"
                :picker-options="pickeroptionsend"
                placeholder="选择日期"
                style="width: 100%;"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-form-item>

        <el-form-item label="活动说明" prop="activityExplain">
          <tinymce v-if="showtinymce" v-model="form.activityExplain" :is-oss="upload.isOss" :height="300" />
        </el-form-item>

        <el-form-item label="出题数量" prop="questionNumber">
          <el-input v-model.number="form.questionNumber" placeholder="请输入出题数量" @focus="type = 2" />
        </el-form-item>
        <el-form-item label="答题成功题数" prop="succNumber">
          <el-input v-model.number="form.succNumber" placeholder="请输入答题成功题数" />
        </el-form-item>
        <el-form-item label="每题分值" prop="questionScore">
          <el-input v-model.number="form.questionScore" placeholder="请输入每题分值" />
        </el-form-item>
        <el-form-item label="答题成功分值系数" prop="succScoreCoefficient">
          <el-input v-model="form.succScoreCoefficient" placeholder="请输入答题成功分值系数" />
        </el-form-item>
        <el-form-item label="答题失败分值系数" prop="failScoreCoefficent">
          <el-input v-model="form.failScoreCoefficent" placeholder="请输入答题失败分值系数" />
        </el-form-item>
        <el-form-item label="答题时长（秒)" prop="breakthroughDuration">
          <el-input v-model.number="form.breakthroughDuration" placeholder="请输入答题时长" />
        </el-form-item>
        <!-- <el-form-item label="成功积分" :prop="points4s == '1' ? 'succPoints': ''">
          <el-row>
            <el-col :span="6">
              <el-input v-model="form.succPoints" :disabled="points4s == -1 || points4s == -9999" placeholder="请输入成功积分" />
            </el-col>
            <el-col :span="2">&nbsp;</el-col>
            <el-col :span="16">
              <el-radio-group v-model="points4s">
                <el-radio :label="1">自定义</el-radio>
                <el-radio :label="-1">跟答题成功分值一致</el-radio>
                <el-radio :label="-9999">跟系统配置一致</el-radio>
              </el-radio-group>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="失败积分" :prop="points4f == '1' ? 'failPoints': ''">
          <el-row>
            <el-col :span="6">
              <el-input v-model="form.failPoints" :disabled="points4f == -1 || points4f == -9999" placeholder="请输入失败积分" />
            </el-col>
            <el-col :span="2">&nbsp;</el-col>
            <el-col :span="16">
              <el-radio-group v-model="points4f">
                <el-radio :label="1">自定义</el-radio>
                <el-radio :label="-1">跟答题失败分值一致</el-radio>
                <el-radio :label="-9999">跟系统配置一致</el-radio>
              </el-radio-group>
            </el-col>
          </el-row>
        </el-form-item> -->
        <!-- <el-form-item label="每日积分上限">
          <el-row>
            <el-col :span="6">
              <el-input :disabled="unlimited" v-model.number="form.everydayPointsLimit" placeholder="每日积分上限" />
            </el-col>
            <el-checkbox style="margin-left: 20px;" v-model="unlimited">无上限</el-checkbox>
          </el-row>
        </el-form-item> -->
        <el-form-item label="每日答题次数" prop="dailyFrequency">
          <el-input v-model.number="form.dailyFrequency" placeholder="请输入每日答题次数" />
        </el-form-item>
        <el-form-item label="展示排名数量" prop="rankLimitNum">
          <el-input v-model.number="form.rankLimitNum" placeholder="请输入排行榜展示人数" :disabled="numberType" style="width: 750px;margin-right: 20px" />
          <el-checkbox v-model="numberType">不限</el-checkbox>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model.number="form.sort" placeholder="请输入排序号（值越大，越靠前）" />
        </el-form-item>
      </el-form>
    </section>

    <div class="manage-footer">
      <el-button style="padding: 8px 30px;" @click="handleCancel">取消</el-button>
      <el-button style="padding: 8px 30px;" type="primary" @click="handleSubmit">确定</el-button>
    </div>
  </section>
</template>
<script>
import { specialText, int, doublescore, intwith, havaInt } from '@/utils/validate'
import ImageUpload from '@/components/ImageUpload'
import { getDictByCode, queryLottery, insert, update, get } from '../api/special'
import Tinymce from '@/components/Tinymce'
export default {
  name: 'NoSpecialManage',
  components: { ImageUpload, Tinymce },
  data() {
    return {
      state: 'create',
      unlimited: true, // 每日积分是否上限
      formloading: false,
      showtinymce: false,
      numberType: false,
      form: {
        id: '',
        deptId: '-1',
        classifyId: '', // type
        activityName: '',
        activityBackgroundColor: '',
        activityImg: '',
        activityBackgroundImg: 'no',
        activityExplain: '',
        activityStartTime: '',
        activityEndTime: '',
        questionNumber: '',
        succNumber: '',
        questionScore: '1',
        succScoreCoefficient: '1',
        failScoreCoefficent: '1',
        breakthroughDuration: '',
        succPoints: '',
        failPoints: '',
        sort: '',
        status: 'ZT02',
        dailyFrequency: '1',
        succIsBigturntable: '0',
        bigturntableId: '',
        everydayPointsLimit: '',
        rankLimitNum: ''// 统计人数
      },
      rules: {
        /* classifyId: [
          { required: true, message: '请选择答题类型 ', trigger: 'change' }
        ],*/
        activityName: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { validator: specialText, trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        activityExplain: [{ required: true, message: '请输入活动说明', trigger: 'blur' }],
        activityBackgroundColor: [{ required: true, message: '请选择活动背景色', trigger: 'blur' }],
        activityImg: [{ required: true, message: '请上传活动图片', trigger: 'blur' }],
        activityBackgroundImg: [{ required: true, message: '请上传活动背景图片', trigger: 'blur' }],
        activityStartTime: [{ required: true, message: '请选择开始日期', trigger: 'blur' }],
        activityEndTime: [{ required: true, message: '请选择结束日期', trigger: 'blur' }],
        questionNumber: [
          { required: true, message: '请输入出题数量', trigger: 'blur' },
          { trigger: 'blur', validator: int }
        ],
        succNumber: [
          { required: true, message: '请输入答题成功题数', trigger: 'blur' },
          { trigger: 'blur', validator: intwith }
        ],
        rankLimitNum: [
          // { required: false, trigger: 'blur' },
          { trigger: 'blur', validator: havaInt }
        ],
        questionScore: [
          { required: true, message: '请输入每题分值', trigger: 'blur' },
          { trigger: 'blur', validator: doublescore }
        ],
        succScoreCoefficient: [
          { required: true, message: '请输答题成功分值系数', trigger: 'blur' },
          { trigger: 'blur', validator: doublescore }
        ],
        failScoreCoefficent: [
          { required: true, message: '请输入答题失败分值系数', trigger: 'blur' },
          { trigger: 'blur', validator: doublescore }
        ],
        breakthroughDuration: [
          { required: true, message: '请输入答题时长', trigger: 'blur' },
          { trigger: 'blur', validator: int }
        ],
        succPoints: [
          { required: true, message: '请输入成功积分', trigger: 'blur' },
          { trigger: 'blur', validator: doublescore }
        ],
        failPoints: [
          { required: true, message: '请输入失败积分', trigger: 'blur' },
          { trigger: 'blur', validator: doublescore }
        ],
        dailyFrequency: [
          { required: true, message: '请输入每日答题次数', trigger: 'blur' },
          { trigger: 'blur', validator: int }
        ],
        succIsBigturntable: [
          { required: true, message: '请选择答题成功是否抽奖', trigger: 'blur' }
        ],
        bigturntableId: [
          { required: true, message: '请选择抽奖活动', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'blur' }
        ]
      },
      points4s: -9999,
      points4f: -9999,
      upload: {
        viewId: '',
        view: '/API-DOCUMENT/document/file/download?id=',
        imagecropperKey: 0,
        isOss: sessionStorage.getItem('FILE_SAVE_THIRD_CONFIG') || false
      },
      upload4bg: {
        viewId: '',
        view: '/API-DOCUMENT/document/file/download?id=',
        imagecropperKey: 0
      },
      dict: {
        ZT: [], // 状态
        HDZXFXPC: [] // type
      },
      lotterys: [],
      type: 1,
      pickeroptionsstart: {
        disabledDate: (time) => {
          if (this.form.activityEndTime) {
            return (
              time.getTime() > new Date(this.form.activityEndTime).getTime()
            )
          }
        }
      },
      pickeroptionsend: {
        disabledDate: (time) => {
          if (this.form.activityStartTime) {
            return (
              time.getTime() < new Date(this.form.activityStartTime).getTime()
            )
          }
        }
      }
    }
  },
  watch: {
    unlimited(val) {
      if (val) {
        this.form.everydayPointsLimit = -1
      } else {
        this.form.everydayPointsLimit = ''
      }
    },
    'form.questionNumber': {
      handler(newName, oldName) {
        if (newName && this.type === 2) {
          this.form.succNumber = newName
          this.form.breakthroughDuration = Number(newName) * 15
        }
      },
      immediate: true,
      deep: true
    },
    'form.succNumber': {
      handler(newName, oldName) {
        if (Number(newName) > this.form.questionNumber) {
          this.$message({
            showClose: true,
            message: '成功题数不能大于出题数！',
            type: 'warning'
          })
          this.form.succNumber = this.form.questionNumber
        }
      },
      immediate: true,
      deep: true
    },
    'form.succIsBigturntable': {
      handler(newName, oldName) {
        if (newName) {
          if (this.form.bigturntableId === -1 || this.form.bigturntableId === '-1') {
            this.form.bigturntableId = ''
          }
        }
      },
      immediate: true,
      deep: true
    },
    'points4s': {
      handler(newName, oldName) {
        this.form.succPoints = newName
      },
      immediate: true,
      deep: true
    },
    'points4f': {
      handler(newName, oldName) {
        this.form.failPoints = newName
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    this.state = this.$route.query.type === 'c' ? 'create' : 'update'
    for (const key in this.dict) {
      this.getDict(key)
    }
    this.getLottery()
    if (this.$route.query.type === 'u') {
      if (this.$route.query.i) {
        this.getData(this.$route.query.i)
      } else {
        this.$message({
          showClose: true,
          message: '参数异常！',
          type: 'warning',
          onClose: () => {
            this.$router.back()
          }
        })
      }
    } else {
      this.showtinymce = true
    }
  },
  methods: {
    /**
     * 获取字典
     */
    getDict(code) {
      return new Promise((resolve, reject) => {
        getDictByCode(code).then(res => {
          this.dict[code] = (res.data.data && res.data.data.length > 0) ? res.data.data[0].list : []
        }).catch(error => {
          reject(error)
        })
      })
    },

    getLottery() {
      return new Promise((resolve, reject) => {
        queryLottery({ status: 'BIGTSTATUS01' }).then(res => {
          this.lotterys = res.data.data || []
        }).catch(error => {
          reject(error)
        })
      })
    },

    handleSubmit() {
      this.state === 'create' ? this.createData() : this.updateData()
    },

    handleCancel() {
      this.$router.push({ path: this.$filterPath('index') })
    },

    /*
    * 新增
    * */
    createData() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          if (this.numberType) {
            this.form.rankLimitNum = -9999
          }
          const params = Object.assign({}, this.form)
          params['bigturntableId'] = (this.form.succIsBigturntable === 0 || this.form.succIsBigturntable === '0') ? '-1' : this.form.bigturntableId
          return new Promise((resolve, reject) => {
            insert(params).then(() => {
              loading.close()
              this.$message({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 1500
              })
              this.$router.push({ path: this.$filterPath('index') })
            }).catch(error => {
              reject(error)
              loading.close()
            })
          })
        }
      })
    },

    /**
     * 编辑提交
     */
    updateData() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          if (this.numberType) {
            this.form.rankLimitNum = -9999
          }
          const params = Object.assign({}, this.form)
          params['bigturntableId'] = (this.form.succIsBigturntable === 0 || this.form.succIsBigturntable === '0') ? '-1' : this.form.bigturntableId
          return new Promise((resolve, reject) => {
            update(params).then(() => {
              loading.close()
              this.dialogFormVisible = false
              this.$message({
                title: '成功',
                message: '编辑成功',
                type: 'success',
                duration: 2000
              })
              this.$router.push({ path: this.$filterPath('index') })
            }).catch(error => {
              reject(error)
              loading.close()
            })
          })
        }
      })
    },

    cancel() {
      this.$router.push({ path: this.$filterPath('index') })
    },

    /**
     * 获取详情
     */
    getData(id) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        get(id).then(res => {
          loading.close()
          const data = res.data.data
          for (const key in this.form) {
            if (key === 'activityImg') {
              this.form[key] = data.activityImg || ''
              this.upload.viewId = data.activityImgUrl || ''
            } else if (key === 'succPoints') {
              this.points4s = data[key]
              this.form[key] = data[key]
            } else if (key === 'rankLimitNum') {
              if (data['rankLimitNum'] === -9999) {
                this.form.rankLimitNum = ''
                this.numberType = true
                this.disabled = true
              } else {
                this.form[key] = data[key]
              }
            } else if (key === 'failPoints') {
              this.points4f = data[key]
              this.form[key] = data[key]
            } else if (key === 'everydayPointsLimit' && data[key] && data[key] === -1) {
              this.unlimited = true
            } else {
              this.form[key] = data[key]
            }
          }
          this.showArea = true
          this.showtinymce = true
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    }
  }
}
</script>
<style lang="scss">
.special-manage {
  background-color: #fff;
  min-height: calc(100vh - 60px);
  max-height: calc(100vh - 60px);
  overflow: hidden;
  .manage-title {
    position: relative;
    height: 40px;
    line-height: 40px;
    padding: 0 20px;
    background-color: #ffffff;
    border-bottom: 1px solid #e5e5e5;
    font-family: PingFangSC-Medium;
    font-weight: bold;
    color: rgba(51, 51, 51, 1);
    font-size: 14px;
    &:before {
      content: '';
      position: absolute;
      width: 2px;
      @include bg-color($mainColor);
      top: 13px;
      bottom: 13px;
      left: 15px;
    }
  }

  .manage-main {
    position: absolute;
    top: 50px;
    left: 0;
    right: 0;
    bottom: 52px;
    box-sizing: border-box;
    padding: 0 10px;
    overflow: hidden;
    &::-webkit-scrollbar {
      width: 8px; /*对垂直流动条有效*/
      height: 1px; /*对水平流动条有效*/
    }
    /** 滚动条轨道*/
    &::-webkit-scrollbar-track {
      box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
      background-color: white;
      border-radius: 3px;
    }
    /** 滚动条里面小方块*/
    &::-webkit-scrollbar-thumb {
      height: 32px;
      border-radius: 5px;
      box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.1);
      background-color: #eaeaea;
    }
    &:hover {
      overflow: auto;
    }
  }

  .main-form {
    width: 1000px !important;
    margin: 0 auto;
    .line {
      text-align: center;
    }
    .form-card {
      margin-top: 20px;
      .el-card__body {
        max-width: 90%;
        margin: 0 auto;
      }
    }
  }

  .manage-footer {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    text-align: center;
    padding: 10px 0;
    background-color: white;
    box-shadow: 0 -3px 6px #f5f5f5;
  }
}
</style>
